﻿/*

Copyright (c) 2009, Stephen Remde
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the <organization> nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY STEPHEN REMDE ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL STEPHEN REMDE BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;

namespace WikiMiner
{
    public class Relatedness : JSPTask
    {
        static int ToSave = 0;

        private class _Store
        {
            public string a, b;
            public float r;

            public override bool Equals(object obj)
            {
                _Store o = obj as _Store;
                return a.Equals(o.a) && b.EndsWith(o.b);
            }
            public override int GetHashCode()
            {
                return a.GetHashCode() ^ b.GetHashCode();
            }
        }

        private const int bits = 0xffff;
        private static List<_Store>[] cache = new List<_Store>[bits + 1];

        static Relatedness()
        {
            for (int i = 0; i <= bits; i++)
                cache[i] = new List<_Store>();

            Load();
        }

        private static void Load()
        {
            try
            {
                StreamReader sr = new StreamReader("relatedness.cache", Encoding.Unicode);

                string line = null;
                while ((line = sr.ReadLine()) != null)
                {
                    string[] split = line.Split('\t');
                    _Store s = new _Store() { a = split[0], b = split[1], r = float.Parse(split[2]) };
                    cache[s.GetHashCode() & bits].Add(s);
                }

                sr.Close();
            }
            catch
            {
            }
        }

        private static bool Saving = false;
        public static void Save()
        {
            if (!Saving && ToSave > 0)
            {
                lock (cache)
                {
                    Saving = true;

                    StreamWriter sw = new StreamWriter(File.Create("relatedness.cache"), Encoding.Unicode);

                    foreach (var l in cache)
                    {
                        lock (l)
                        {
                            foreach (var entry in l)
                            {
                                sw.WriteLine(entry.a + '\t' + entry.b + '\t' + entry.r);
                            }
                        }
                    }

                    sw.Close();

                    Saving = false;
                }
                
                ToSave = 0;             
            }
        }

        public static float Get(string article1, string article2)
        {
            string articlea = article1.ToLower();

            if (articlea.Contains("(disambiguation)"))
                return 0;


            string articleb = article2.ToLower();

            if (articleb.Contains("(disambiguation)"))
                return 0;

            
            int a = articleb.CompareTo(articlea);

            if (a == 0)
            {
                return 1;
            }
            else if (a < 0)
            {
                string tmp = articlea;
                articlea = articleb;
                articleb = tmp;
            }
            


            _Store s = new _Store() { a = articlea, b = articleb };
            
            var ca = cache[s.GetHashCode() & bits];

            lock (ca)
            {
                foreach (var entry in ca)
                    if (entry.a == articlea && entry.b == articleb)
                        return entry.r;
            }

            try
            {
                XmlDocument doc = GetXml(string.Format(compareurl, Uri.EscapeDataString(articlea), Uri.EscapeDataString(articleb)));

                string value = doc.SelectSingleNode("WikipediaMinerResponse/RelatednessResponse").Attributes["relatedness"].Value;

                float rel = float.Parse(value);

                s.r = rel;

            }
            catch
            {

            }

            lock (cache)
            {
                lock (ca)
                {
                    ca.Add(s);
                }
            }

            ToSave++;

            return s.r;
        }

        internal static void Add(string article1, string article2, float rel)
        {
            string articlea = article1.ToLower();
            string articleb = article2.ToLower();

            int a = articleb.CompareTo(articlea);

            if (a < 0)
            {
                string tmp = articlea;
                articlea = articleb;
                articleb = tmp;
            }
            else if (a==0)
            {
                return;
            }
            
            _Store s = new _Store() { a = articlea, b = articleb, r = rel };
            
            var ca = cache[s.GetHashCode() & bits];

            lock (cache)
            {
                lock (ca)
                {
                    ca.Add(s);
                    ToSave++;
                }
            }
        }
    }
}
